use crate::{AppError, AppResult, Menu, MenuType, PageResult, QueryParams, UserStatus};
use chrono::Utc;
use std::collections::HashMap;
use std::sync::Mutex;
use uuid::Uuid;

// 内存中的菜单数据存储
lazy_static::lazy_static! {
    static ref MENUS: Mutex<HashMap<String, Menu>> = Mutex::new(HashMap::new());
}

// 初始化示例菜单数据
fn init_sample_menus() {
    let mut menus = MENUS.lock().unwrap();
    
    // 添加示例菜单
    let sample_menus = vec![
        Menu {
            id: "menu_001".to_string(),
            name: "系统管理".to_string(),
            path: None,
            component: None,
            icon: Some("Setting".to_string()),
            parent_id: None,
            order_num: 1,
            menu_type: MenuType::Directory,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(30),
            update_time: Utc::now() - chrono::Duration::days(5),
        },
        Menu {
            id: "menu_002".to_string(),
            name: "用户管理".to_string(),
            path: Some("/system/user".to_string()),
            component: Some("system/user/index".to_string()),
            icon: Some("User".to_string()),
            parent_id: Some("menu_001".to_string()),
            order_num: 1,
            menu_type: MenuType::Menu,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(25),
            update_time: Utc::now() - chrono::Duration::days(3),
        },
        Menu {
            id: "menu_003".to_string(),
            name: "角色管理".to_string(),
            path: Some("/system/role".to_string()),
            component: Some("system/role/index".to_string()),
            icon: Some("UserFilled".to_string()),
            parent_id: Some("menu_001".to_string()),
            order_num: 2,
            menu_type: MenuType::Menu,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(20),
            update_time: Utc::now() - chrono::Duration::days(1),
        },
        Menu {
            id: "menu_004".to_string(),
            name: "SIP管理".to_string(),
            path: None,
            component: None,
            icon: Some("Phone".to_string()),
            parent_id: None,
            order_num: 2,
            menu_type: MenuType::Directory,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(30),
            update_time: Utc::now() - chrono::Duration::days(5),
        },
        Menu {
            id: "menu_005".to_string(),
            name: "通话管理".to_string(),
            path: Some("/sip/call".to_string()),
            component: Some("sip/call/index".to_string()),
            icon: Some("Phone".to_string()),
            parent_id: Some("menu_004".to_string()),
            order_num: 1,
            menu_type: MenuType::Menu,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(25),
            update_time: Utc::now() - chrono::Duration::days(3),
        },
        Menu {
            id: "menu_006".to_string(),
            name: "注册管理".to_string(),
            path: Some("/sip/register".to_string()),
            component: Some("sip/register/index".to_string()),
            icon: Some("Connection".to_string()),
            parent_id: Some("menu_004".to_string()),
            order_num: 2,
            menu_type: MenuType::Menu,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(20),
            update_time: Utc::now() - chrono::Duration::days(1),
        },
        Menu {
            id: "menu_007".to_string(),
            name: "系统监控".to_string(),
            path: None,
            component: None,
            icon: Some("Monitor".to_string()),
            parent_id: None,
            order_num: 3,
            menu_type: MenuType::Directory,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(30),
            update_time: Utc::now() - chrono::Duration::days(5),
        },
        Menu {
            id: "menu_008".to_string(),
            name: "在线用户".to_string(),
            path: Some("/monitor/online".to_string()),
            component: Some("monitor/online/index".to_string()),
            icon: Some("User".to_string()),
            parent_id: Some("menu_007".to_string()),
            order_num: 1,
            menu_type: MenuType::Menu,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(25),
            update_time: Utc::now() - chrono::Duration::days(3),
        },
        Menu {
            id: "menu_009".to_string(),
            name: "定时任务".to_string(),
            path: Some("/monitor/job".to_string()),
            component: Some("monitor/job/index".to_string()),
            icon: Some("Timer".to_string()),
            parent_id: Some("menu_007".to_string()),
            order_num: 2,
            menu_type: MenuType::Menu,
            status: UserStatus::Active,
            children: vec![],
            create_time: Utc::now() - chrono::Duration::days(20),
            update_time: Utc::now() - chrono::Duration::days(1),
        },
    ];
    
    for menu in sample_menus {
        menus.insert(menu.id.clone(), menu);
    }
}

#[tauri::command]
pub async fn get_menu_list(params: QueryParams) -> AppResult<PageResult<Menu>> {
    // 初始化示例数据
    init_sample_menus();
    
    let menus = MENUS.lock().unwrap();
    let mut menu_list: Vec<Menu> = menus.values().cloned().collect();
    
    // 应用过滤条件
    if let Some(keyword) = &params.keyword {
        if !keyword.is_empty() {
            menu_list.retain(|menu| {
                menu.name.contains(keyword) ||
                menu.path.as_ref().map_or(false, |path| path.contains(keyword)) ||
                menu.component.as_ref().map_or(false, |comp| comp.contains(keyword))
            });
        }
    }
    
    if let Some(status) = &params.status {
        if !status.is_empty() {
            let status_value: i32 = status.parse().unwrap_or(0);
            menu_list.retain(|menu| {
                let menu_status: i32 = menu.status.clone().into();
                menu_status == status_value
            });
        }
    }
    
    // 构建树形结构
    let tree_menus = build_menu_tree(&menu_list);
    
    // 分页处理
    let (list, total) = crate::utils::Utils::paginate(
        &tree_menus,
        params.page,
        params.size,
    );
    
    Ok(PageResult {
        list,
        total,
        page: params.page.unwrap_or(1),
        size: params.size.unwrap_or(10),
    })
}

#[tauri::command]
pub async fn create_menu(mut menu: Menu) -> AppResult<Menu> {
    // 验证必填字段
    if menu.name.is_empty() {
        return Err(AppError::ValidationError("菜单名称不能为空".to_string()));
    }
    
    // 设置菜单ID和时间
    menu.id = Uuid::new_v4().to_string();
    menu.create_time = Utc::now();
    menu.update_time = Utc::now();
    
    // 保存菜单
    let mut menus = MENUS.lock().unwrap();
    menus.insert(menu.id.clone(), menu.clone());
    
    Ok(menu)
}

#[tauri::command]
pub async fn update_menu(mut menu: Menu) -> AppResult<Menu> {
    let mut menus = MENUS.lock().unwrap();
    
    if let Some(existing_menu) = menus.get_mut(&menu.id) {
        // 更新字段
        existing_menu.name = menu.name;
        existing_menu.path = menu.path;
        existing_menu.component = menu.component;
        existing_menu.icon = menu.icon;
        existing_menu.parent_id = menu.parent_id;
        existing_menu.order_num = menu.order_num;
        existing_menu.menu_type = menu.menu_type;
        existing_menu.status = menu.status;
        existing_menu.update_time = Utc::now();
        
        Ok(existing_menu.clone())
    } else {
        Err(AppError::NotFoundError("菜单不存在".to_string()))
    }
}

#[tauri::command]
pub async fn delete_menu(menu_id: String) -> AppResult<()> {
    let mut menus = MENUS.lock().unwrap();
    
    // 检查是否有子菜单
    let has_children = menus.values().any(|menu| menu.parent_id == Some(menu_id.clone()));
    if has_children {
        return Err(AppError::ValidationError("请先删除子菜单".to_string()));
    }
    
    if menus.remove(&menu_id).is_some() {
        Ok(())
    } else {
        Err(AppError::NotFoundError("菜单不存在".to_string()))
    }
}

#[tauri::command]
pub async fn update_menu_status(menu_id: String, status: i32) -> AppResult<()> {
    let mut menus = MENUS.lock().unwrap();
    
    if let Some(menu) = menus.get_mut(&menu_id) {
        menu.status = status.into();
        menu.update_time = Utc::now();
        Ok(())
    } else {
        Err(AppError::NotFoundError("菜单不存在".to_string()))
    }
}

#[tauri::command]
pub async fn get_menu_by_id(menu_id: String) -> AppResult<Menu> {
    let menus = MENUS.lock().unwrap();
    
    menus
        .get(&menu_id)
        .cloned()
        .ok_or_else(|| AppError::NotFoundError("菜单不存在".to_string()))
}

#[tauri::command]
pub async fn get_menu_tree() -> AppResult<Vec<Menu>> {
    let menus = MENUS.lock().unwrap();
    let menu_list: Vec<Menu> = menus.values().cloned().collect();
    
    Ok(build_menu_tree(&menu_list))
}

// 构建菜单树形结构
fn build_menu_tree(menus: &[Menu]) -> Vec<Menu> {
    let mut menu_map: HashMap<String, Menu> = HashMap::new();
    let mut root_menus: Vec<Menu> = Vec::new();
    
    // 创建菜单映射
    for menu in menus {
        menu_map.insert(menu.id.clone(), menu.clone());
    }
    
    // 构建树形结构
    for menu in menus {
        if let Some(parent_id) = &menu.parent_id {
            if let Some(parent_menu) = menu_map.get_mut(parent_id) {
                parent_menu.children.push(menu.clone());
            }
        } else {
            root_menus.push(menu.clone());
        }
    }
    
    // 按order_num排序
    root_menus.sort_by(|a, b| a.order_num.cmp(&b.order_num));
    
    root_menus
}
